package com.leectrl.utils;

public class HexUtil {

    /**
     * 字节数组转16进制
     * @param b 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytes2HexString(byte[] b) {
        StringBuffer result = new StringBuffer();

        String hex;

        for (int i = 0; i < b.length; i++) {
            hex = Integer.toHexString(b[i] & 0xFF);

            if (hex.length() == 1) {
                hex = '0' + hex;

            }

            result.append(hex.toUpperCase());

        }

        return result.toString();
    }

    public static String hexToText(String inHex){
        byte[] bytes=hexToByteArray(inHex);
        StringBuffer result=new StringBuffer();
        for(byte b:bytes){
            result.append((char)b);
        }
        return result.toString();
    }

    /**
     * Hex字符串转byte
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte
     */
    public static byte hexToByte(String inHex){
        return (byte)Integer.parseInt(inHex,16);
    }

    /**
     * hex字符串转byte数组
     * @param inHex 待转换的Hex字符串
     * @return  转换后的byte数组结果
     */
    public static byte[] hexToByteArray(String inHex){
        int hexlen = inHex.length();
        byte[] result;
        if (hexlen % 2 == 1){
            //奇数
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {
            //偶数
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2){
            result[j]=hexToByte(inHex.substring(i,i+2));
            j++;
        }
        return result;
    }


    public static String reserveHex(String hexStr) {
        if (hexStr==null) {
            return null;
        }
        if(hexStr.length() % 2 != 0){
            hexStr="0"+hexStr;
        }
        StringBuffer sb = new StringBuffer();
        int length = hexStr.length() / 2;
        for (int i = length-1; i >=0; i--) {
            sb.append(hexStr.substring(i * 2, (i + 1) * 2));
        }
        return sb.toString();
    }

    public static boolean isHexStr(String hexStr) {
        if(hexStr==null||hexStr.length()==0){
            return false;
        }
        String lowerCaseStr=hexStr.toLowerCase();
        for(int i=0;i<lowerCaseStr.length();i++){
            int code=lowerCaseStr.charAt(i);
            if(!((code>=48&&code<=57)||((code>=97&&code<=102)))){
                return false;
            }
        }
        return true;
    }

}
